package org.whuims.pois.report.chart2Pic;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.StandardChartTheme;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.title.LegendTitle;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.time.Day;
import org.jfree.data.time.Month;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.ui.RectangleInsets;
import org.joda.time.DateTime;
import org.whuims.pois.dao.NewsDao;
import org.whuims.pois.helper.ReportDataHelper;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by john on 2015/5/22.
 */
public class Chart2PNG {
//    public static final String PATH = "F:/Test/";
    public static final String PATH = "/info/data/pdf_temp/";

    //站点
    public static List<File> newsSiteTrend(String start, String end, long topicId, String language, String type) {
        List<Map<String, Long>> maps = new NewsDao().sitedist(null, topicId, language, start, end);
        List<String> fileName = new ArrayList<String>();  // TODO 文件命名
        for (int i = 0; i < maps.size(); i++) {
            String s = PATH + filename(topicId + "", start, end, getType(i));
            fileName.add(s);
        }
        return drowNewsSiteTrend(maps, fileName);
    }

    private static String getType(int i) {
        switch (i) {
            case 0:
                return "news";
            case 1:
                return "bbs";
            case 2:
                return "weibo";
            case 3:
                return "blog";
            case 4:
                return "weixin";
        }
        return "";
    }

    private static String getTypeName(int i) {
        switch (i) {
            case 0:
                return "新闻";
            case 1:
                return "论坛";
            case 2:
                return "微博";
            case 3:
                return "博客";
            case 4:
                return "微信";
        }
        return "";
    }

    public static String filename(String topic, String start, String end, String type) {
        return topic + "_" + start + "_" + end + "_" + type + "_" + new Random().nextInt(1000) + ".png";
    }

    //时间
    public static List<File> newsTimeTrend(String start, String end, long topicId, String type) {

        List<List<Calendar>> list = new NewsDao().timeserial(type, topicId, null, start, end);
        List<Map<String, Long>> result = ReportDataHelper.timedata(list);
        List<TreeMap<String, Long>> dataset = new ArrayList<TreeMap<String, Long>>();
        List<String> fileName = new ArrayList<String>();
        for (int i = 0; i < result.size(); i++) {
            Map<String, Long> map = result.get(i);
            TreeMap<String, Long> treemap = new TreeMap<String, Long>(map);
            dataset.add(treemap);
            fileName.add(PATH + filename(topicId + "", start, end, getType(i)));  // TODO 文件命名
        }
        return drowNewsTimeTrend(dataset, fileName);

    }

    public static List<File> drowNewsSiteTrend(List<Map<String, Long>> dataset, List<String> fileName) {
        List<File> files = new ArrayList<File>();
        for (int i = 0; i < fileName.size(); i++) {
            File file = new File(fileName.get(i));
            Map<String, Long> map = dataset.get(i);
            Set<Map.Entry<String, Long>> set = map.entrySet();
            DefaultCategoryDataset dataset1 = new DefaultCategoryDataset();
            int j = 0;
            for (Map.Entry<String, Long> entry : set) {
                j++;
                String site = entry.getKey();
                long times = entry.getValue();
                dataset1.addValue(times, site, site);
            }

            setTheme();

            JFreeChart chart = ChartFactory.createBarChart3D("", "站点",
                    "数量", dataset1, PlotOrientation.VERTICAL, true, false,
                    false);
            chart.setTitle(getTypeName(i) + " 站点统计");
            try {
                ChartUtilities.saveChartAsPNG(file, chart, 500, 350);
                files.add(file);
                System.out.println("绘画完成");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return files;
    }

    public static List<File> drowNewsTimeTrend(List<TreeMap<String, Long>> dataSet, List<String> fileName) {
        List<File> files = new ArrayList<File>();
        for (int i = 0; i < fileName.size(); i++) {
            File file = new File(fileName.get(i));
            TreeMap<String, Long> map = dataSet.get(i);
            Set<Map.Entry<String, Long>> set = map.entrySet();
            Iterator<Map.Entry<String, Long>> iterator = set.iterator();
            Map.Entry<String, Long> first = iterator.next();
            String date = first.getKey();

            String monthRegex = "\\d{4}-\\d{1,2}";
            Pattern monthPattern = Pattern.compile(monthRegex);
            Matcher matcher = monthPattern.matcher(date);

            String dayRegex = "\\d{4}-\\d{1,2}-\\d{1,2}";
            Pattern dayPattern = Pattern.compile(dayRegex);
            Matcher dayMatcher = dayPattern.matcher(date);

            // 时间间隔以月为单位
            if (matcher.matches()) {
                TimeSeries timeSeries = new TimeSeries("", Month.class);
                TimeSeriesCollection lineDataset = new TimeSeriesCollection();
                for (Map.Entry<String, Long> entry : set) {
                    String s = entry.getKey();
                    long times = entry.getValue();
                    String[] strings = s.split("-");
                    int year = Integer.parseInt(strings[0]);
                    int month = Integer.parseInt(strings[1]);
                    timeSeries.add(new Month(month, year), times);
                }

                //设置主题
                setTheme();
                lineDataset.addSeries(timeSeries);
                JFreeChart chart = ChartFactory.createTimeSeriesChart("", "时间", "数量", lineDataset, true, true, true);
                setFont(chart, i);

                XYPlot plot = (XYPlot) chart.getPlot();
                plot.getRangeAxis().setLowerBound(0);
                plot.getRangeAxis().setAutoRangeMinimumSize(1);
                plot.setAxisOffset(new RectangleInsets(10, 10, 10, 10));
                plot.setOutlinePaint(Color.PINK);
                try {
                    ChartUtilities.saveChartAsPNG(file, chart, 500, 250);
                    files.add(file);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            // 时间间隔以天为单位
            if (dayMatcher.matches()) {

                TimeSeries timeSeries = new TimeSeries("", Day.class);
                TimeSeriesCollection lineDataset = new TimeSeriesCollection();

                for (Map.Entry<String, Long> entry : set) {
                    String s = entry.getKey();
                    long times = entry.getValue();
                    String[] strings = s.split("-");
                    int year = Integer.parseInt(strings[0]);
                    int month = Integer.parseInt(strings[1]);
                    int day = Integer.parseInt(strings[2]);
                    timeSeries.add(new Day(day, month, year), times);
                }

                lineDataset.addSeries(timeSeries);
                //设置主题
                setTheme();

                JFreeChart chart = ChartFactory.createTimeSeriesChart("", "日期", "数量", lineDataset, true, true, true);
                setFont(chart, i);
                XYPlot plot = (XYPlot) chart.getPlot();
                plot.getRangeAxis().setLowerBound(0);
                plot.getRangeAxis().setAutoRangeMinimumSize(1);
                chart.setAntiAlias(true);
                plot.setAxisOffset(new RectangleInsets(10, 10, 10, 10));
                plot.setOutlinePaint(Color.PINK);
                try {
                    ChartUtilities.saveChartAsPNG(file, chart, 500, 250);
                    files.add(file);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return files;

    }

    private static void setFont(JFreeChart chart, int i) {
        chart.setTitle(new TextTitle(getTypeName(i) + " 走势分析"));
        chart.setAntiAlias(true);
        chart.getTitle().setFont(new Font("宋体", Font.BOLD, 13));
        LegendTitle lt = chart.getLegend();
        if (lt != null) {
            lt.setItemFont(new Font("宋体", Font.BOLD, 13));
        }
    }

    private static void setTheme() {
        StandardChartTheme standardChartTheme = new StandardChartTheme("CN");
        standardChartTheme.setExtraLargeFont(new Font("宋体", Font.BOLD, 15));
        standardChartTheme.setRegularFont(new Font("宋体", Font.PLAIN, 12));
        standardChartTheme.setLargeFont(new Font("宋体", Font.PLAIN, 12));
        ChartFactory.setChartTheme(standardChartTheme);
    }

    public static void main(String[] args) {
        DateTime now = new DateTime();
        DateTime past = now.minusDays(10);
        List<File> files = new Chart2PNG().newsSiteTrend("2015-05-01", "2015-05-07", 6, null, null);
        List<File> files1 = Chart2PNG.newsTimeTrend("2015-05-01", "2015-05-07", 6, null);
        System.out.println(files);
        System.out.println(files1);
    }
}
